#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
简化版打包脚本 - 直接使用PyInstaller命令
"""

import os
import sys
import subprocess
from pathlib import Path

def main():
    print("=" * 60)
    print("🚀 PySide6 GUI应用简化打包")
    print("=" * 60)
    
    # 切换到项目根目录
    project_root = Path(__file__).parent.parent.parent
    os.chdir(project_root)
    
    print(f"📁 项目根目录: {project_root}")
    
    # 检查GUI文件是否存在
    gui_file = project_root / "gui" / "pro" / "发票_美化版.py"
    if not gui_file.exists():
        print(f"❌ GUI文件不存在: {gui_file}")
        return
    
    print(f"✅ GUI文件存在: {gui_file.name}")
    
    # 构建命令
    build_cmd = [
        sys.executable, "-m", "PyInstaller",
        str(gui_file),
        "--name", "发票识别工具_美化版",
        "--onefile",  # 打包成单个exe文件
        "--windowed",  # 隐藏控制台窗口
        "--clean",     # 清理临时文件
        "--noconfirm", # 不确认覆盖
        "--distpath", str(project_root / "gui" / "pro"),  # 指定输出目录
        "--add-data", f"{project_root / 'poocr'};poocr",  # 添加poocr包
        "--hidden-import", "poocr",
        "--hidden-import", "loguru",
        "--hidden-import", "PySide6.QtCore",
        "--hidden-import", "PySide6.QtGui", 
        "--hidden-import", "PySide6.QtWidgets",
    ]
    
    print("\n🔧 构建命令:")
    print(" ".join(build_cmd))
    
    print("\n🚀 开始构建...")
    
    try:
        # 执行构建命令
        result = subprocess.run(build_cmd, capture_output=True, text=True, encoding='utf-8')
        
        if result.returncode == 0:
            print("✅ 构建成功!")
            
            # 显示构建结果
            dist_dir = project_root / "gui" / "pro"
            if dist_dir.exists():
                exe_files = list(dist_dir.glob("*.exe"))
                if exe_files:
                    print(f"\n📦 生成的可执行文件:")
                    for exe in exe_files:
                        print(f"   - {exe.name}")
                        print(f"     📁 路径: {exe}")
                        print(f"     📏 大小: {exe.stat().st_size / (1024*1024):.2f} MB")
                else:
                    print("⚠️  未找到可执行文件")
            
            print("\n🎉 打包完成!")
            print("\n📋 使用说明:")
            print("1. 可执行文件位于: gui/pro/ 目录")
            print("2. 双击运行即可使用")
            print("3. 无需安装Python环境")
            
        else:
            print("❌ 构建失败!")
            print("\n📋 错误信息:")
            print(result.stderr)
            
    except Exception as e:
        print(f"❌ 构建过程中发生错误: {e}")
    
    print("\n" + "=" * 60)
    print("✨ 打包流程完成")
    print("=" * 60)

if __name__ == "__main__":
    main()